//package com.example.account;
//
//import androidx.appcompat.app.AppCompatActivity;
//import androidx.viewpager.widget.ViewPager;
//
//import android.os.Bundle;
//import android.util.Log;
//import android.view.View;
//import android.widget.TextView;
//
//import com.example.account.Adapter.AnalysePagerAdapter;
//import com.example.account.DataBase.AccountDataBase;
//import com.example.account.DataBase.AccountDataDao;
//import com.google.android.material.tabs.TabLayout;
//
//public class AnalyseActivity extends AppCompatActivity {
//    private TabLayout tabLayout;
//    private ViewPager viewPager;
//    private TextView tvTotalIncome;
//    private TextView tvTotalExpense;
//    private AccountDataDao accountDataDao;
//
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_analyse);
//
//        tabLayout = findViewById(R.id.tab_layout);
//        viewPager = findViewById(R.id.view_pager);
//        tvTotalIncome = findViewById(R.id.tv_total_income);
//        tvTotalExpense = findViewById(R.id.tv_total_expense);
//
//        // 检查 TextView 是否为 null
//        if (tvTotalIncome == null) {
//            Log.e("AnalyseActivity", "tvTotalIncome is null");
//        }
//        if (tvTotalExpense == null) {
//            Log.e("AnalyseActivity", "tvTotalExpense is null");
//        }
//
//        accountDataDao = AccountDataBase.getDatabase(getApplicationContext()).getDataDao();
//
//        // 检查 accountDataDao 是否为 null
//        if (accountDataDao == null) {
//            Log.e("AnalyseActivity", "accountDataDao is null");
//        }
//
//        setupViewPager();
//        setupTabLayout();
//        updateTotalIncomeAndExpense();
//    }
//
//    private void setupViewPager() {
//        AnalysePagerAdapter adapter = new AnalysePagerAdapter(getSupportFragmentManager());
//        adapter.addFragment(new ExpenseAnalyseFragment(), "支出分析");
//        adapter.addFragment(new IncomeAnalyseFragment(), "收入分析");
//        viewPager.setAdapter(adapter);
//    }
//
//    private void setupTabLayout() {
//        tabLayout.setupWithViewPager(viewPager);
//    }
//
//    private void updateTotalIncomeAndExpense() {
//        float totalIncome = accountDataDao.qaskMoneySum(1);
//        float totalExpense = accountDataDao.qaskMoneySum(0);
//
//        if (tvTotalIncome != null) {
//            tvTotalIncome.setText("总收入: " + String.format("%.2f", totalIncome));
//        } else {
//            Log.e("AnalyseActivity", "tvTotalIncome is null");
//        }
//
//        if (tvTotalExpense != null) {
//            tvTotalExpense.setText("总支出: " + String.format("%.2f", totalExpense));
//        } else {
//            Log.e("AnalyseActivity", "tvTotalExpense is null");
//        }
//    }
//
//    public void record_back(View view) {
//        long startTime = System.currentTimeMillis();
//        finish();
//        Log.d("AnalyseActivity", "Time taken to finish: " + (System.currentTimeMillis() - startTime) + " ms");
//    }
//
//}


package com.example.account;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.account.Adapter.AnalysePagerAdapter;
import com.example.account.DataBase.AccountDataBase;
import com.example.account.DataBase.AccountDataDao;
import com.google.android.material.tabs.TabLayout;

import java.util.Calendar;

public class AnalyseActivity extends AppCompatActivity {
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private TextView tvTotalIncome;
    private TextView tvTotalExpense;
    private AccountDataDao accountDataDao;
    private ImageView calendarIcon;
    private int selectedYear, selectedMonth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_analyse);

        tabLayout = findViewById(R.id.tab_layout);
        viewPager = findViewById(R.id.view_pager);
        tvTotalIncome = findViewById(R.id.tv_total_income);
        tvTotalExpense = findViewById(R.id.tv_total_expense);
        calendarIcon = findViewById(R.id.his_rili);

        // 检查 TextView 是否为 null
        if (tvTotalIncome == null) {
            Log.e("AnalyseActivity", "tvTotalIncome is null");
        }
        if (tvTotalExpense == null) {
            Log.e("AnalyseActivity", "tvTotalExpense is null");
        }

        accountDataDao = AccountDataBase.getDatabase(getApplicationContext()).getDataDao();

        // 检查 accountDataDao 是否为 null
        if (accountDataDao == null) {
            Log.e("AnalyseActivity", "accountDataDao is null");
        }

        setupViewPager();
        setupTabLayout();

        // 获取当前系统时间
        Calendar calendar = Calendar.getInstance();
        selectedYear = calendar.get(Calendar.YEAR);
        selectedMonth = calendar.get(Calendar.MONTH) + 1; // 月份从0开始，所以需要加1

        // 默认加载当前月份的数据
        loadDataForSelectedDate();

        calendarIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog();
            }
        });
    }

    private void setupViewPager() {
        AnalysePagerAdapter adapter = new AnalysePagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new ExpenseAnalyseFragment(), "支出分析");
        adapter.addFragment(new IncomeAnalyseFragment(), "收入分析");
        viewPager.setAdapter(adapter);
    }

    private void setupTabLayout() {
        tabLayout.setupWithViewPager(viewPager);
    }

    public void record_back(View view) {
        long startTime = System.currentTimeMillis();
        finish();
        Log.d("AnalyseActivity", "Time taken to finish: " + (System.currentTimeMillis() - startTime) + " ms");
    }

    private void showDatePickerDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = getLayoutInflater().inflate(R.layout.dialog_his, null);
        final DatePicker datePicker = view.findViewById(R.id.date_picker_his);
        builder.setView(view);

        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(System.currentTimeMillis());
        datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null);
        hideDay(datePicker);

        builder.setPositiveButton("确  定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                selectedYear = datePicker.getYear();
                selectedMonth = datePicker.getMonth() + 1; // 月份从0开始，所以需要加1

                // 根据选定的日期加载数据
                loadDataForSelectedDate();
                dialog.cancel(); // 取消dialog
            }
        });

        AlertDialog dialog = builder.create();
        dialog.show();
    }

    private void hideDay(DatePicker datePicker) {
        try {
            int daySpinnerId = getResources().getIdentifier("day", "id", "android");
            if (daySpinnerId != 0) {
                View daySpinner = datePicker.findViewById(daySpinnerId);
                if (daySpinner != null) {
                    daySpinner.setVisibility(View.GONE); // 隐藏天数选择器
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void loadDataForSelectedDate() {
        // 在这里根据选定的日期加载数据
        // 你可以调用你的 Fragment 中的方法来更新数据
        ExpenseAnalyseFragment expenseFragment = (ExpenseAnalyseFragment) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.view_pager + ":" + 0);
        IncomeAnalyseFragment incomeFragment = (IncomeAnalyseFragment) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.view_pager + ":" + 1);

        if (expenseFragment != null) {
            expenseFragment.updateData(selectedYear, selectedMonth);
        }

        if (incomeFragment != null) {
            incomeFragment.updateData(selectedYear, selectedMonth);
        }

        // 更新总收入和总支出
        updateTotalIncomeAndExpenseForSelectedDate();
    }

    private void updateTotalIncomeAndExpenseForSelectedDate() {
        float totalIncome = accountDataDao.query_Money_by_month_type(1, selectedMonth, selectedYear);
        float totalExpense = accountDataDao.query_Money_by_month_type(0, selectedMonth, selectedYear);

        if (tvTotalIncome != null) {
            tvTotalIncome.setText("总收入: " + String.format("%.2f", totalIncome));
        } else {
            Log.e("AnalyseActivity", "tvTotalIncome is null");
        }

        if (tvTotalExpense != null) {
            tvTotalExpense.setText("总支出: " + String.format("%.2f", totalExpense));
        } else {
            Log.e("AnalyseActivity", "tvTotalExpense is null");
        }
    }
}